package main

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"
)
func init(){
	f,err:=os.OpenFile("log.log",os.O_CREATE|os.O_APPEND|os.O_RDWR,os.ModePerm)
	if err !=nil{
		panic(err)
	}
	multiWriter:=io.MultiWriter(os.Stdout,f)
	log.SetOutput(multiWriter)
	log.SetPrefix("[log]")
	log.SetFlags(log.LstdFlags|log.Lshortfile|log.Ldate)

	return
}

type Game struct {
	Url string
	Client *http.Client
	Times int
	Wg *sync.WaitGroup
	Token string
}

func (g *Game) RoundStr() string {
	rand.Seed(time.Now().UnixNano())
	timeT :=200 + rand.Intn(4800)
	return strconv.Itoa(timeT)
}

func (g *Game) RunGame() (string,error){
	url:=g.Url+"game_over?rank_score=1&rank_state=1&rank_time="+g.RoundStr()+"&rank_role=1&skin=1"
	return g.Run(url)

}

func (g *Game) RunTopic() (string,error) {
	url:=g.Url+"topic_game_over?rank_score=1&rank_state=1&rank_time="+g.RoundStr()+"&rank_role=2&skin=1"
	return g.Run(url)

}

func (g *Game) PlayGame()  {
	defer g.Wg.Done()
	for i:=0;i<g.Times;i++ {
		//res, _ := g.RunTopic()
		res,err:=g.RunGame()
		if err !=nil{
			log.Println(err)
		}
		_,err2:=g.RunTopic()
		if err2 !=nil{
			log.Println(err2)
		}
		log.Println("第",i,"次通关游戏")
		log.Println(res)
	}
}

func (g *Game) Run(url string) (string,error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}
	req.Header=DefaultHeader
	req.Header.Add("t",g.Token)
	resp, err := g.Client.Do(req)

	if err != nil {
		return "", err
	}
	bodyText, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(bodyText), nil
}

func main() {

	jsonFile,err:=ioutil.ReadFile("config.json")
	if err!=nil{
		log.Printf("configFile.Get err #%v",err)
	}
	config :=Config{}
	err = json.Unmarshal(jsonFile,&config)
	if err!=nil{
		log.Printf("Unmarshal err #%v",err)
	}
   token:=GetToken(config.Uid)
   N := 1
	game:=Game{
		Url:"https://cat-match.easygame2021.com/sheep/v1/game/",
		Client:&http.Client{Timeout: time.Second*30},
		Wg: &sync.WaitGroup{} ,
		Times: config.Times,
		Token:token,
	}
	for i:=0;i<N;i++{
		game.Wg.Add(1)
		go game.PlayGame()
	}
	game.Wg.Wait()
	log.Printf("game over")
}
